package com.sample.plove.authener.util;

import com.sample.plove.authener.config.WechatConfig;
import com.sample.plove.authener.model.BasicAuthParam;
import com.sample.plove.authener.model.response.AuthAccessToken;
import com.sample.plove.authener.model.response.AuthUserInfo;
import com.sample.plove.authener.server.WechatAuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * PackageName:com.sample.plove.authener.util
 * Author:Administrator
 * Time:20:48
 * Date:2019/5/21
 * Describe:
 *
 * @author Administrator
 */
@Slf4j
public class WechatUtil {
    /**
     * 拼接微信Authorized的地址
     *
     * @return
     */
    public static String getUserAuthUrl(WechatAuthService authService) {
        BasicAuthParam basicAuthParam = new BasicAuthParam() {
            @Override
            public Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("appid", WechatConfig.APP_ID);
                params.put("redirect_uri", "http://plove.ngrok.xiaomiqiu.cn/we/resultCode");
                params.put("response_type", "code");
                params.put("scope", "snsapi_userinfo");
                params.put("state", "123");
                return params;
            }
        };

        String result = authService.getAuthUrl(basicAuthParam, WechatConfig.AUTHORIZE_OAUTH_URL);
        log.info(result);
        return result;
    }

    /**
     * 请求通过code获取网页授权,获取AccessToken
     *
     * @param code code
     * @return token
     */
    public static AuthAccessToken getAuthAccessToken(WechatAuthService authService, String code) {
        BasicAuthParam basicAuthParam = new BasicAuthParam() {
            @Override
            public Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("appid", WechatConfig.APP_ID);
                params.put("secret", WechatConfig.APP_SECRET);
                params.put("code", code);
                params.put("grant_type", "authorization_code");
                return params;
            }
        };
        return authService.getAuthAccessToken(basicAuthParam, WechatConfig.GET_OAUTH_TOKEN_URL);
    }

    /**
     * 获取用户信息
     *
     * @param accessToken token
     * @param openid      openid
     * @return 用户信息
     */
    public static AuthUserInfo getAuthUserInfo(WechatAuthService authService, String accessToken, String openid) {
        return authService.getAuthUserInfo(accessToken, openid);
    }
}
